package com.xingfly.mq;

import com.xingfly.constant.MQConstant;
import com.xingfly.model.Event;
import com.xingfly.model.Feed;
import com.xingfly.repository.FeedRepository;
import com.xingfly.repository.FriendRepository;
import com.xingfly.repository.UserRepository;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by SuperS on 15/05/2017.
 *
 * @author SuperS
 */
@Component
//监听FEED_MQ队列
@RabbitListener(queues = MQConstant.FEED_MQ)
public class FeedReceiver {
    @Autowired
    private FeedRepository feedRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FriendRepository friendRepository;

    //处理器 处理接收到事件对象
    @RabbitHandler
    public void process(Event e) {
        //获取事件创建者的所有粉丝
        List<Long> fansId = friendRepository.findByUserAllFansId(e.getUser().getId());
        //遍历创建Feed写入数据库
        for (Long id : fansId) {
            Feed feed = new Feed();
            feed.setEvent(e);
            feed.setFans(userRepository.findOne(id));
            feed.setAuthor(e.getUser());
            feedRepository.save(feed);
        }
    }
}
